package com.bridgetree.jubaocrm.ui.project;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.JsonObjectPostRequest;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.ui.Contents;
import com.bridgetree.jubaocrm.ui.ProgressDialogUtil;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.Projects;
import com.bridgetree.jubaocrm.ui.LoginUtil;
/**
 *添加联系人
 */
public class XMChildAddContactsActivity extends Activity {
	
	private Context mContext;
	private final String TAG ="XMChildAddContactsActivity";
	private Projects mProjects;
	private InputMethodManager mInputMethodManager ;
	private String user_id =""; 
	private String token ="";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xmlxr);
		mContext=this;
		
		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
		user_id = prefs.getString(Contents.KEY_PERSONAL_LOGIN_USEID, ""); 
		token = prefs.getString(Contents.KEY_PERSONAL_LOGIN_TAKEN, "");
		
		TextView xm_lxr_tv_title =(TextView)findViewById(R.id.xm_lxr_tv_title);
		if(intent.getExtras()!=null){
			mProjects = (Projects)intent.getExtras().getSerializable("my_projects");
			xm_lxr_tv_title.setText("客户联系人");
		}
		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
		
		findViewById(R.id.xm_lxr_RelativeLayout_back).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		
		findViewById(R.id.xm_lxr_bt_ok).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getAddContacts();
			}
		});
		
		EditText et1EditText=(EditText) findViewById(R.id.xm_lxr_ed_name);
		et1EditText.setFocusable(true);   
		et1EditText.setFocusableInTouchMode(true);   
		et1EditText.requestFocus(); 
	}
	
	private void openDailog(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title)
		.setMessage(content).setPositiveButton("确定", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void getAddContacts() {
		EditText xm_lxr_ed_name = (EditText) findViewById(R.id.xm_lxr_ed_name);
		EditText xm_lxr_ed_tp = (EditText) findViewById(R.id.xm_lxr_ed_tp);
		EditText xm_lxr_ed_call = (EditText) findViewById(R.id.xm_lxr_ed_call);
		EditText xm_lxr_ed_weixin = (EditText) findViewById(R.id.xm_lxr_ed_weixin);
		EditText xm_lxr_ed_qq = (EditText) findViewById(R.id.xm_lxr_ed_qq);
		EditText xm_lxr_ed_msn = (EditText) findViewById(R.id.xm_lxr_ed_msn);
		EditText xm_lxr_ed_mail = (EditText) findViewById(R.id.xm_lxr_ed_mail);
		EditText xm_lxr_ed_work = (EditText) findViewById(R.id.xm_lxr_ed_work);
		EditText xm_lxr_ed_txt = (EditText) findViewById(R.id.xm_lxr_ed_txt);
		
		String fullname = xm_lxr_ed_name.getText().toString();
		String tp = xm_lxr_ed_tp.getText().toString();
		String call = xm_lxr_ed_call.getText().toString();
		String weixin = xm_lxr_ed_weixin.getText().toString();
		String qq = xm_lxr_ed_qq.getText().toString();
		String msn = xm_lxr_ed_msn.getText().toString();
		String mail = xm_lxr_ed_mail.getText().toString();
		String work = xm_lxr_ed_work.getText().toString();
		String txt = xm_lxr_ed_txt.getText().toString();
		String tmp ="";
		if(fullname.equals("")|| fullname.length()<2 || fullname.length()>50){
			tmp+="姓名必须是2-50个字符\n";
		}
		if(tp.equals("")){
		}else if(tp.length()<7 || tp.length()>20){
			tmp+="手机必须是7-20个字符\n";
		}
		if(call.equals("")){
		}else if(call.length()<8 || call.length()>20){
			tmp+="座机必须是8-20个字符\n";
		}
		if(qq.equals("")){
		}else if(qq.length()<4 || qq.length()>15){
			tmp+="qq必须是4-15个字符\n";
		}
		if(mail.equals("")){
		}else if(!mail.contains("@")){
			tmp+="邮件格式错误\n";
		}
		if(work.equals("")){
		}else if(work.length()<2 || work.length()>20){
			tmp+="职位必须是2-20个字符\n";
		}
		if(txt.equals("")){
		}else if(txt.length()<2 || txt.length()>20){
			tmp+="备注必须是2-20个字符\n";
		}
		
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailog("网络提示", "网络未连接,请连接网络！");
		} else if (!tmp.equals("")) {
			openDailog("失败提示", tmp);
		} else{
			final ProgressDialog progressDialog=ProgressDialogUtil.show(mContext);
			HashMap<String, String> mMap = new HashMap<String, String>();
			mMap.put("action", "add");
			mMap.put("cellphone", xm_lxr_ed_tp.getText().toString());
			mMap.put("client_id", mProjects.getClient_id());
			mMap.put("commit", xm_lxr_ed_txt.getText().toString());
			mMap.put("email", xm_lxr_ed_mail.getText().toString());
			mMap.put("fixed_phone", xm_lxr_ed_call.getText().toString());
			mMap.put("fullname", xm_lxr_ed_name.getText().toString());
			mMap.put("job", xm_lxr_ed_work.getText().toString());
			mMap.put("msn", xm_lxr_ed_msn.getText().toString());
			mMap.put("project_id", mProjects.getProject_id());
			mMap.put("qq", xm_lxr_ed_qq.getText().toString());
			mMap.put("token", token);
			mMap.put("user_id", user_id);
			mMap.put("validation", CRMUserBaseInfo.kValication);
			mMap.put("weixin", xm_lxr_ed_weixin.getText().toString());
			String URL = Network.API_DOMAIN+"/project/contact";

			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectPostRequest jsonObjectPostRequest = new JsonObjectPostRequest(
					URL, new Response.Listener<JSONObject>() {

						@Override
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										finish();
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr.length(); i++) {
													JSONObject jsonObj2 = jsonArr.getJSONObject(i);
													if (!jsonObj2.isNull("desc")) {
														String desc = jsonObj2.getString("desc");
														openDailog("失败提示", desc);
														mLoginError.setDesc(desc);
													}
													if (!jsonObj2.isNull("value")) {
														String value = jsonObj2.getString("value");
														mLoginError.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {
							ProgressDialogUtil.dissmis(progressDialog);
							Toast.makeText(mContext, "网络未连接！",
									Toast.LENGTH_LONG).show();
						}
					}, mMap);
			requestQueue.add(jsonObjectPostRequest);
		}

	}

}

